/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates.gate.logic;

import dale2507.gates.GatePlugin;
import dale2507.gates.Messenger;
import dale2507.gates.data.Settings;
import dale2507.gates.exceptions.GateConnectionException;
import dale2507.gates.exceptions.PermissionException;
import dale2507.gates.gate.Activator;
import dale2507.gates.gate.Gate;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitScheduler;

/**
 *
 * @author Dale
 */
public class FailBeforeDial extends IActivatorLogic {
    
    private BukkitScheduler scheduler = Bukkit.getScheduler();
    private int dialler;
    
    public FailBeforeDial(Activator activator, CommandSender cs) {
        super(activator, cs);
    }

    @Override
    public void run() {
        try {
            getActivator().findDestination();
            getActivator().checkDestination();
        
            this.getActivator().setSourceStatus(Gate.Status.DIALLING);
            this.getActivator().setDestinationStatus(Gate.Status.RECEIVING);
            
            dialler = this.scheduler.scheduleAsyncRepeatingTask(GatePlugin.getInstance(), 
                    new Dialler(), 
                    Settings.getInstance().connection.chevronDelay(), 
                    Settings.getInstance().connection.chevronDelay());
        } catch (GateConnectionException | PermissionException ex) {
            sendMessage(Messenger.ERROR, ex.getMessage());
        }
    }

    @Override
    public void stop() {
        scheduler.cancelTask(dialler);
    }
    
    private class Dialler implements Runnable {
        
        private boolean lastDial = false;
        private int ticker = 0;

        @Override
        public void run() {
            if (!lastDial) {
                lastDial = getActivator().dialChevron(ticker);
                ticker++;
            } else {
                getActivator().establish();
                scheduler.cancelTask(dialler);
            }
        }
        
    }
}
